package com.example.elderlycare.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.elderlycare.dao.entity.Role;
import com.example.elderlycare.dao.entity.User;
import com.example.elderlycare.dao.mapper.RoleMapper;
import com.example.elderlycare.dao.mapper.UserMapper;
import com.example.elderlycare.service.UserService;
import com.example.elderlycare.service.entity.QueryListResponseBody;
import com.example.elderlycare.service.entity.UserItem;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    UserMapper userMapper;

    @Resource
    RoleMapper roleMapper;

    @Override
    public QueryListResponseBody<UserItem> queryUserList(int current, int pageSize, QueryWrapper<User> queryWrapper) {
        List<Role> roleList = roleMapper.selectList(null);
        Map<Integer, Role> roleMap = new HashMap<>(5);
        roleList.forEach(role -> roleMap.put(role.getId(), role));

        Page<User> page = new Page<>(current, pageSize);
        Page<User> userPage = userMapper.selectPage(page, queryWrapper);
        int total = (int) userPage.getTotal();
        List<User> userList = userPage.getRecords();
        List<UserItem> userItemList = new ArrayList<>();
        userList.forEach(user -> {
            UserItem userItem = UserItem.builder()
                    .id(user.getId())
                    .nickname(user.getNickname())
                    .username(user.getUsername())
                    .number(user.getNumber())
                    .phone(user.getPhone())
                    .sex(user.getSex())
                    .vxId(user.getVxId())
                    .roleId(user.getRoleID())
                    .role(roleMap.get(user.getRoleID()).getName())
                    .build();
            userItemList.add(userItem);
        });
        QueryListResponseBody.QueryListResponseBodyBuilder<UserItem> queryListResponseBodyBuilder = QueryListResponseBody.builder();
        return queryListResponseBodyBuilder
                .total(total)
                .items(userItemList)
                .build();
    }
}
